#include <vector>
#include <queue>
#include "sched_rr.h"
#include "basesched.h"
#include <iostream>
#include <fstream>

using namespace std;

SchedRR::SchedRR(vector<int> argn) {
	// Round robin recibe la cantidad de cores y sus cpu_quantum por parámetro
	cores = argn[0];
	for(int i = 0; i < cores; i++ ){
		quantum.push_back(argn[i+1]);
		quantum_left.push_back(argn[i+1]);
	}
}

SchedRR::~SchedRR() {


}


void SchedRR::load(int pid) {
	tareas.push(pid);
}

void SchedRR::unblock(int pid) {
	load(pid);
}

int SchedRR::tick(int cpu, const enum Motivo m) {
	
	
	if(m == TICK && (current_pid(cpu)!=IDLE_TASK)){
		
		
		//resto 1 al quantum_left[cpu]
		quantum_left[cpu]--; 
		//si no queda quantum, restauro el quantum y pido la proxima tarea --> next()
		
		if(quantum_left[cpu] == 0){
			tareas.push(current_pid(cpu));
			return next(cpu);
		}else {
			return current_pid(cpu);
		}
	}
	// Si es BLOCK o EXIT, solo pido next()
	
	return next(cpu);
}

int SchedRR::next(int cpu) {
	//restauro el quantum_left
		if(tareas.empty()){
			quantum_left[cpu] = quantum[cpu];
			return IDLE_TASK;
	}else {
		int next_task = tareas.front();
		tareas.pop();
		quantum_left[cpu] = quantum[cpu];
		return next_task;
	}
	
}
